import dayjs from "dayjs";
import { message } from "@/utils/message";
// import { getUserList } from "@/api/system";
import { ElMessageBox } from "element-plus";
import { type PaginationProps } from "@pureadmin/table";
import { reactive, ref, computed, onMounted } from "vue";

export function dataMerging() {
  const form = reactive({
    username: "",
    mobile: "",
    status: ""
  });
  const dataList = ref([]);
  const companyListSelected = ref([]);
  const companyListAll = ref([]);
  const loading = ref(true);
  const switchLoadMap = ref({});
  const pagination = reactive<PaginationProps>({
    total: 0,
    pageSize: 10,
    currentPage: 1,
    background: true
  });
  const dialogFormVisible = ref(false);
  const dialogForm = ref();
  const dialogFormRef = reactive({
    companyListSelected: []
  });
  const dialogState = ref("");
  const dialogTitle = ref("");
  const validateName = (rule, value, callback) => {
    if (value == "" || value == null || !value) {
      callback(new Error("请选择公司！"));
    } else if (value.length == 1) {
      callback(new Error("请选择多个公司进行合并！"));
    } else {
      callback();
    }
  };
  const rules = reactive({
    companyListSelected: [
      { required: false, validator: validateName, trigger: ["blur"] }
    ]
  });
  const columns: TableColumnList = [
    {
      type: "selection",
      width: 55,
      align: "left"
    },
    {
      label: "序号",
      type: "index",
      width: 70,
      hide: ({ checkList }) => !checkList.includes("序号列")
    },
    {
      label: "数据源合并",
      prop: "mergeCode",
      width: 400
    },
    {
      label: "数据源合并名称显示",
      prop: "username",
      minWidth: 130
    }
  ];
  const buttonClass = computed(() => {
    return [
      "!h-[20px]",
      "reset-margin",
      "!text-gray-500",
      "dark:!text-white",
      "dark:hover:!text-primary"
    ];
  });

  function onChange({ row, index }) {
    ElMessageBox.confirm(
      `确认要<strong>${
        row.status === 0 ? "停用" : "启用"
      }</strong><strong style='color:var(--el-color-primary)'>${
        row.username
      }</strong>用户吗?`,
      "系统提示",
      {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
        dangerouslyUseHTMLString: true,
        draggable: true
      }
    )
      .then(() => {
        switchLoadMap.value[index] = Object.assign(
          {},
          switchLoadMap.value[index],
          {
            loading: true
          }
        );
        setTimeout(() => {
          switchLoadMap.value[index] = Object.assign(
            {},
            switchLoadMap.value[index],
            {
              loading: false
            }
          );
          message("已成功修改用户状态", {
            type: "success"
          });
        }, 300);
      })
      .catch(() => {
        row.status === 0 ? (row.status = 1) : (row.status = 0);
      });
  }

  function handleUpdate(row) {
    console.log(row);
  }

  function handleDelete(row) {
    console.log(row);
  }

  function handleSizeChange(val: number) {
    console.log(`${val} items per page`);
  }

  function handleCurrentChange(val: number) {
    console.log(`current page: ${val}`);
  }

  function handleSelectionChange(val) {
    console.log("handleSelectionChange", val);
  }

  function queryCompanyList() {
    companyListAll.value = [
      "中储南京智慧物流科技有限公司",
      "金湖分公司",
      "淮安分公司",
      "中储南京智慧物流科技有限公司美国加利福尼亚分公司",
      "中储南京智慧物流科技有限公司匹兹堡分公司"
    ];
  }

  function openDialog(type: string, row?: {}) {
    dialogState.value = type;
    queryCompanyList();
    if (type == "add") {
      dialogTitle.value = "新增数据源合并";
    } else {
      dialogTitle.value = "修改数据源合并";
      console.log(row);
    }
    dialogFormVisible.value = true;
  }

  function submitDialog() {
    dialogForm.value.validate(validate => {
      if (validate) {
        dialogFormVisible.value = false;
      }
    });
  }

  function handleClose() {
    dialogForm.value.clearValidate();
    dialogFormVisible.value = false;
  }

  async function onSearch() {
    loading.value = true;
    // const { data } = await getUserList();
    const data = {
      list: [
        {
          username: "中储南京智慧物流科技有限公司,金湖分公司",
          mergeCode: "ZCZY,JH",
          remark: "管理员",
          deptId: 103,
          postIds: [1],
          mobile: "15888888888",
          sex: 0,
          id: "ZCZB",
          status: 0,
          createTime: 1609837427000,
          dept: { id: 103, name: "研发部门" }
        }
      ],
      total: 1
    };
    dataList.value = data.list;
    pagination.total = data.total;
    setTimeout(() => {
      loading.value = false;
    }, 500);
  }

  const resetForm = formEl => {
    if (!formEl) return;
    formEl.resetFields();
    onSearch();
  };

  onMounted(() => {
    onSearch();
  });

  return {
    form,
    loading,
    columns,
    companyListSelected,
    companyListAll,
    dataList,
    pagination,
    buttonClass,
    dialogFormVisible,
    dialogFormRef,
    dialogForm,
    rules,
    dialogTitle,
    dialogState,
    handleClose,
    submitDialog,
    openDialog,
    onSearch,
    resetForm,
    handleUpdate,
    handleDelete,
    handleSizeChange,
    handleCurrentChange,
    handleSelectionChange
  };
}
